package com.thghh.ch5.huffman;

import java.util.ArrayList;
import java.util.List;


/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/10/12 10:04
 */
public class TraverseFactory<E> {

    private List<Traverse<E>> list;
    private Traverse<E> traverse;

    public TraverseFactory() {
        list = new ArrayList<>();
    }

    public TraverseFactory(Traverse<E> traverse) {
        this.traverse = traverse;
        list = new ArrayList<>();
    }

    public List<Traverse<E>> traverse(TraverseType type) {
        return traverse(traverse, type);
    }

    public List<Traverse<E>> traverse(Traverse<E> traverse, TraverseType type) {
        list.clear();
        switch (type) {
            case VLR: // 前
                vlr(traverse);
                break;
            case LDR: // 中
                ldr(traverse);
                break;
            case LRD: // 后
                lrd(traverse);
                break;
        }
        return list;
    }

    private void vlr(Traverse<E> traverse) {
        list.add(traverse);
        if (traverse.getLeft() != null)
            vlr(traverse.getLeft());
        if (traverse.getRight() != null)
            vlr(traverse.getRight());
    }

    private void ldr(Traverse<E> traverse) {
        if (traverse.getLeft() != null)
            ldr(traverse.getLeft());
        list.add(traverse);
        if (traverse.getRight() != null)
            ldr(traverse.getRight());
    }

    private void lrd(Traverse<E> traverse) {
        if (traverse.getLeft() != null)
            lrd(traverse.getLeft());
        if (traverse.getRight() != null)
            lrd(traverse.getRight());
        list.add(traverse);
    }
}

